package com.qxzn.app.page.banner;

import android.content.ComponentName;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.AuthInfoBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.FamilyMemberBean;
import com.qxzn.app.bean.Recreation;
import com.qxzn.app.page.R;
import com.qxzn.app.page.WebActivity;
import com.qxzn.app.page.widget.ToastUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.LinkedList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 应用内跳转，广告banner轮番图跳转，消息中心跳转
 */
public class BannerHelper {

    public static void jumping(FragmentActivity activity, String type_param) {
        jumping(activity, type_param, null, null);
    }

    public static void jumping(FragmentActivity activity, String type_param, String robot_code, String name) {
        String[] params = type_param.split("&");
        if (params.length == 0) return;
        LinkedList<String> strings = new LinkedList<>(Arrays.asList(params));
        if ("com".equals(strings.poll()) && !strings.isEmpty()) {
            switch (strings.poll()) {
                case "app": {
                    jumpingApp(activity, strings, robot_code, name);
                }
                break;
                case "html":
                    if (!strings.isEmpty()) {
//                        activity.startActivity();
                        try {
                            activity.startActivity(new Intent(activity, WebActivity.class)
                                    .putExtra("url", URLDecoder.decode(strings.poll(), "UTF-8")));
//                            ToastUtil.showTextToast(activity, "跳转网页：" + URLDecoder.decode(strings.poll(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
        }
    }

    private static void jumpingApp(FragmentActivity activity, LinkedList<String> params, String robot_code, String username) {
        if (params.isEmpty()) return;
        switch (params.poll()) {
            case "addRobot":
                if ("addMember".equals(params.poll())) {
                    addMember(activity, params, robot_code, username);
                }
                break;
            case "skill":
//                ToastUtil.showTextToast(activity, params.toString());
                if ("skillDetail".equals(params.poll())) {
                    try {
                        activity.startActivity(new Intent()
                                .setComponent(new ComponentName(activity, "com.lmc.SkillsDetailsActivity"))
                                .putExtra("id", URLDecoder.decode(params.poll(), "UTF-8").split("=")[1]));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case "health":
                ToastUtil.showTextToast(activity, params.toString());
                break;
            case "entertain":

                if ("entertainMoreList".equals(params.poll())) {
                    try {
                        activity.startActivity(new Intent()
                                .setComponent(new ComponentName(activity, "com.lmc.recreation.RecreationListActivity"))
                                .putExtra("name", username)
                                .putExtra("id", URLDecoder.decode(params.poll(), "UTF-8").split("=")[1]));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case "personal":
                ToastUtil.showTextToast(activity, params.toString());
                break;
            case "communication": // com&app&communication&videoCall&device_id=07a69106f69740074ba868d4fe452a82,device_name=机器人2a82
                if ("videoCall".equals(params.poll())) {
                    try {
                        String[] device = URLDecoder.decode(params.poll(), "UTF-8").split(",");
                        if (device.length == 2) {
                            String[] deviceId = device[0].split("=");
                            String[] deviceName = device[1].split("=");
                            if (deviceId.length == 2 && deviceName.length == 2) {
                                activity.startActivity(new Intent()
                                        .setComponent(new ComponentName(activity, "com.qxzn.module.agora.VideoChatCallActivity"))
                                        .putExtra(deviceId[0], deviceId[1])
                                        .putExtra(deviceName[0], deviceName[1])
                                        .putExtra("user_name", username));
                                break;
                            }
                        }
                        ToastUtil.showTextToast(activity, "数据出错：" + params.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    private static void addMember(FragmentActivity activity, LinkedList<String> params, String robot_code, String username) {
        JSONObject param = new JSONObject();
        param.put("device_id", robot_code);
        HttpRequest.getService().getAuthInfo(HttpRequest.getDefaultBody(param)).enqueue(new Callback<BaseBean<AuthInfoBean>>() {
            @Override
            public void onResponse(Call<BaseBean<AuthInfoBean>> call, Response<BaseBean<AuthInfoBean>> response) {
                BaseBean<AuthInfoBean> body = response.body();
                if (body.getCode() == 200) {
                    AuthInfoBean data = body.getData();
                    if ("1".equals(data.user_role)) {
                        if (TextUtils.equals(username, data.admin_id)) {
                            // 管理员处理请求
                            try {
                                param.put("username", URLDecoder.decode(params.poll(), "UTF-8").split("=")[1]);
                                HttpRequest.getService().getAuthInfo(HttpRequest.getDefaultBody(param)).enqueue(new Callback<BaseBean<AuthInfoBean>>() {
                                    @Override
                                    public void onResponse(Call<BaseBean<AuthInfoBean>> call, Response<BaseBean<AuthInfoBean>> response) {
                                        BaseBean<AuthInfoBean> body = response.body();
                                        if (body.getCode() == 200) {
                                            AuthInfoBean data = body.getData();
                                            if ("1".equals(data.user_role)) {
                                                ToastUtil.showImgToast(activity, "已通过", R.mipmap.icon_success);
                                            } else if ("-3".equals(data.user_role) || "-4".equals(data.user_role)) {
                                                ToastUtil.showImgToast(activity, "已拒绝", R.mipmap.icon_success);
                                            } else {
                                                FamilyMemberBean.MemberBean memberBean = new FamilyMemberBean.MemberBean();
                                                memberBean.setRoles("-1");
                                                memberBean.setNiname(data.user_name);
                                                memberBean.setUsername(data.user_id);
                                                memberBean.setHeadportrait(data.user_pic);
                                                activity.startActivity(new Intent()
                                                        .setComponent(new ComponentName(activity.getApplicationContext(),
                                                                "com.qxzn.module.mine.activity.ViewToJoinFamilyActivity"))
                                                        .putExtra("member_bean", memberBean));

                                            }
                                        } else {
                                            ToastUtil.showTextToast(activity, body.getMsg());
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<BaseBean<AuthInfoBean>> call, Throwable t) {
                                        error(activity);
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            // 已绑定
                            ToastUtil.showImgToast(activity, "已加入家庭圈", R.mipmap.icon_success);
                        }
                    } else if ("-3".equals(data.user_role) || "-4".equals(data.user_role)) {
                        ToastUtil.showImgToast(activity, "已拒绝", R.mipmap.icon_failed);
                    } else {
                        // 成员处理管理员邀请
                        data.user_id = username;
                        activity.startActivity(new Intent()
                                .setComponent(new ComponentName(activity.getApplicationContext(),
                                        "com.qxzn.module.home.activity.RespondJoinFamilyActivity"))
                                .putExtra("AuthInfoBean", data));
                    }
                } else {
                    ToastUtil.showTextToast(activity, body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean<AuthInfoBean>> call, Throwable t) {
                error(activity);
            }
        });
    }

    private static void error(FragmentActivity activity) {
        ToastUtil.showTextToast(activity, activity.getString(R.string.network_error));
    }


}
